# -*- coding: utf-8 -*-
# @Time    : 2025/8/5 10:30
# @Author  : FuKai ZHANG
# @File    : allure_server.py
# @Description : 在报告生成以后后台启动allure服务
import subprocess
import socket
import os
import time
from utils.logging_tools.log_control import INFO, ERROR

def start_allure_server(report_path="./report/html"):
    try:
        if not os.path.exists(report_path):
            ERROR.error(f"报告路径不存在: {report_path}")
            return None

        # 检查关键文件是否存在
        index_file = os.path.join(report_path, "index.html")
        data_dir = os.path.join(report_path, "data")
        if not os.path.exists(index_file) or not os.path.exists(data_dir):
            ERROR.error(f"报告路径缺少必要文件: {report_path}")
            return None

        port = 9000
        host = "0.0.0.0"  # 监听所有网络接口，允许局域网访问
        # 获取本机局域网 IP 地址
        lan_ip = socket.gethostbyname(socket.gethostname())
        url = f"http://{lan_ip}:{port}"
        
        INFO.info(f"正在 {url} 上启动 HTTP 服务器")
        
        # 使用subprocess执行Python命令启动HTTP服务器
        cmd = ["python", "-m", "http.server", str(port), "--directory", report_path]
        
        # 在后台运行 HTTP 服务器
        process = subprocess.Popen(
            cmd,
            stdout=subprocess.DEVNULL,
            stderr=subprocess.DEVNULL
        )

        # 等待片刻以确保服务器启动
        time.sleep(3)

        INFO.info(f"HTTP 服务器已在 {url} 上运行，局域网可访问，进程PID: {process.pid}")
        return url

    except Exception as e:
        ERROR.error(f"启动 HTTP 服务器时出错: {e}")
        return None